//
//  ContentView.swift
//  FNiOS
//
//  Created by mac on 2023/3/13.
//

import SwiftUI
import Flutter
import FlutterPluginRegistrant	    	

import LibShare	
import FlutterBridge

struct ContentView: View {
    
    init(){
        print("初始化页面 \(UIScreen.main.bounds.width) x \(UIScreen.main.bounds.height)")
    }
    
    // Flutter dependencies are passed in an EnvironmentObject.
    @EnvironmentObject var flutterDependencies: FlutterDependencies
    
    var twoRouterHolder:String = "输入路由"
    @State var dartFile:String = ""
    @State var funcName:String = "twoMain"
    @State var rootRoute:String = "root"
    @State var pageRoute:String = "/root"
    
    let routerText = Text("请输入路由")
    
    @State private var routerFocus:Bool = false
    
    var body: some View {
        VStack(spacing:0) {
            // 状态栏
            EmptyView().frame(height: 44)
            
//            EmptyView().frame(height: 44)
            Group {
                // 默认 lib/main.dart
                TextField("输入入口 dart 文件", text: self.$dartFile)
                    .frame(height: 44)
                    .background(Color(red: 230/255, green: 230/255, blue: 230/255))
                // 默认 main 指定其他函数需要添加 注释
                TextField("输入 挂载 函数", text: self.$funcName)
                    .frame(height: 44)
                    .background(Color(red: 250/255, green: 250/255, blue: 250/255))
                // 根路由
                TextField("输入根路由", text: self.$rootRoute)
                    .frame(height: 44)
                    .background(Color(red: 230/255, green: 230/255, blue: 230/255))
                // 页面路由
                TextField("输入页面路由", text: self.$pageRoute)
                    .frame(height: 44)
                    .background(Color(red: 250/255, green: 250/255, blue: 250/255))
                
                Button(action: {
                    print(" 路由地址 \(dartFile) : \(funcName) : \(rootRoute) : \(pageRoute) ")
                    showFlutterRoot(dartFile: self.dartFile, funcName: self.funcName, rootRoute: self.rootRoute, pageRoute: self.pageRoute)
                }) {
                    Text("跳转到指定 Flutter 页面")
                }.padding(EdgeInsets(top: 20, leading: 0, bottom: 0, trailing: 0))
                
                Text("默认 Fluter 界面 lib/main.dart -> mian()")
                    .onTapGesture {
                        showFlutter()
                    }
            }
            // 会给每个子空间增加配置
            .padding(EdgeInsets(top: 0, leading: 8, bottom: 0, trailing: 8))
            
            MyView()
                .background(Color(red: 0.1, green: 0.1, blue: 0.1))
                .onTapGesture {
                    print("====== Framework ======")
                    
                    print("LibShare: " + SharedUtils.SHARE_VERSION)
//                    FlutterBridgeImpl.logd("123")
                    FlutterBridgeLogger.logd(str: "FlutterBridge: "+"123")
                    
                    print("==== 这是自定义 View ====")
                    let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene
                    let window = scene?.windows.first
                    print("\(String(describing: window?.safeAreaInsets.top))")
                    print("\(String(describing: window?.safeAreaInsets.bottom))")
                }
            
            ScrollView {
                NavigationView(content: {
                    NavigationLink {
                        UserLogin()
                    } label: {
                        VStack{
                            Text("前往登录")
                            Text("前往注册")
                            Text("前往实名")
                            Text("前往服务")
                        }
                    }
                })
                .frame(width: 375, height:300)
                .navigationTitle(Text("登录"))
            }.frame(width: 375, height: 300)
                .background(Color(red: 0.1, green: 0.1, blue: 0.1))
                .padding(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
                .edgesIgnoringSafeArea(.all)
                .listRowInsets(EdgeInsets())
            ScrollView {
                Group {	
                    Image("bg_home")
                        .background(Color.blue)
                    
                    Image("bg_home")
                        .clipShape(Circle())
                        .shadow(radius: 7)
                    
                    Image(systemName: "globe")
                        .imageScale(.large)
                        // 遮罩
                        .foregroundColor(Color.red)
                    
                    // 网络请求
                    Text("进行 GET 请求")
                        .onTapGesture {
                            doGet()
                        }
                        .padding(EdgeInsets(top: 20, leading: 0, bottom: 0, trailing: 0))
                    
                    Text("进行 POST 请求")
                        .onTapGesture {
                            doPost()
                        }
                        .padding(EdgeInsets(top: 20, leading: 0, bottom: 0, trailing: 0))
                    EmptyView().background(Color(red: 1, green: 1, blue: 1)).frame(width:375, height: 34)
                }
                .edgesIgnoringSafeArea(.all)
            }
            .background(Color(red: 0.91, green: 0.91, blue: 0.91))
            .padding(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
            .edgesIgnoringSafeArea(.all)
            // 占满
            Spacer()
        }
        // 设置属性的顺序很重要
        .frame(width: 375)
        .background(Color(red: 0.97, green: 0.97, blue: 0.97))
        .padding(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
        .edgesIgnoringSafeArea(.all)
    }
    
    func goToHomeSecond(){
        if let window = UIApplication.shared.windows.first
        {
            window.rootViewController = UIHostingController(rootView: UserLogin())
            window.makeKeyAndVisible()
        }
    }
    
    /**
     * 全局 FlutterEngine 引擎
     */
    func showFlutter(){
        // 获取根控制器 RootViewController
        guard
            let windowScene = UIApplication.shared.connectedScenes
                .first(where: { $0.activationState == .foregroundActive && $0 is UIWindowScene }) as? UIWindowScene,
            let window = windowScene.windows.first(where: \.isKeyWindow),
            let rootViewController = window.rootViewController
        else { return }
        
        // 创建 FlutterViewController 把 flutterEngine 传递给 FlutterViewController
        let flutterViewController = FlutterViewController(
            engine: flutterDependencies.flutterEngine,
            nibName: nil,
            bundle: nil)
        flutterViewController.modalPresentationStyle = .overCurrentContext
        flutterViewController.isViewOpaque = false
        rootViewController.present(flutterViewController, animated: true)
    }
    
    /**
     * 显示指定的 Flutter 界面
     */
    func showFlutterRoot(dartFile:String, funcName:String, rootRoute:String, pageRoute:String) {
        
        // 获取根控制器 RootViewController
        guard let windowScene = UIApplication.shared.connectedScenes
            .first(where: { $0.activationState == .foregroundActive && $0 is UIWindowScene }) as? UIWindowScene,
              let window = windowScene.windows.first(where: \.isKeyWindow),
              let rootViewController = window.rootViewController
        else { return }
        
        // 创建 flutterEngine
        // let flutterEngine = FlutterEngine(name: "root")
        // 通过 FlutterEngineGroup 创建 FlutterEngine
        let flutterProject = FlutterDartProject()
        let engineGroup = FlutterEngineGroup(name: "fn", project: flutterProject)
        let flutterEngine = engineGroup.makeEngine(withEntrypoint: funcName, libraryURI: dartFile, initialRoute:rootRoute)
        flutterEngine.run()
        // 定义入口 函数 以及 路由 -> route -> window.defaultRouteName
        // flutterEngine.run(withEntrypoint: funcName, initialRoute: rootRoute)
        // try? flutterEngine.run(withEntrypoint: "main", libraryURI: "main.dart", initialRoute: router)
        // flutterEngine.run(withEntrypoint: "twoMain", libraryURI: "main.dart", initialRoute: router, entrypointArgs: Array())
        // FlutterEngineGroup.init(name: "FN", project: self)
        
        // 注册引擎
        GeneratedPluginRegistrant.register(with: flutterEngine)
        
        // 创建 FlutterViewController
        let flutterViewController = FlutterViewController(
            engine: flutterEngine,
            nibName: nil,
            bundle: nil)
        
        // 设置 通信通道 : 必须在 flutterEngine run 之后
        let channel =  FlutterMethodChannel(name: "flutter_bridge",
                                            binaryMessenger: flutterEngine.binaryMessenger)
        // 添加回调监听
        channel.setMethodCallHandler({
            (call: FlutterMethodCall, flutterResult: @escaping FlutterResult) -> Void in
            NSLog("%@", call.method)
            switch call.method
            {
            case "Native":
                print("Flutter 调用原生: Native")
                flutterResult("原生的返回， 继续点击累加 +1")
                break;
            case "Channel":
                flutterViewController.pushRoute("/app")
                break;
            case "Text":
                flutterResult("IOS-Text 返回数据， 继续累加 +1")
                break;
            case "Back":
                // Get the RootViewController.
                guard
                    let windowScene = UIApplication.shared.connectedScenes
                        .first(where: { $0.activationState == .foregroundActive && $0 is UIWindowScene }) as? UIWindowScene,
                    let window = windowScene.windows.first(where: \.isKeyWindow),
                    let rootViewController = window.rootViewController
                else { return }
                rootViewController.dismiss(animated: true)
                
                break;
            default:
                break;
            }
        })
        
        // 切换 UIViewController 显示 flutter 界面
        flutterViewController.modalPresentationStyle = .overCurrentContext
        flutterViewController.isViewOpaque = false
        rootViewController.present(flutterViewController, animated: true)
        
        // 切换路由 没用
        // flutterViewController.pushRoute(pageRouter)
        flutterEngine.navigationChannel.invokeMethod("setInitialRoute", arguments: pageRoute)
    }
    
    /**
     * json 字符串 转 字典
     */
    func strToObj(json:String) -> Dictionary<String, Any>{
        let jsonData:Data = json.data(using: String.Encoding.utf8)!
        let resultDic = try? JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers)
        if (resultDic != nil){
            return resultDic as! Dictionary<String,Any>
        }
        return Dictionary()
    }
    
    /**
     * iOS 网络请求 get
     */
    func doGet(){
        // 请求地址
        // let getUrl = URL(string:"http://192.168.43.42:5000")!
        let getUrl = URL(string:"http://192.168.137.1:5000/user/login")!
        // session 会话
        let session = URLSession.shared
        // 请求体
        var request = URLRequest(url:getUrl)
        request.httpMethod = "GET"	
        // 请求头 headers
        request.setValue("application/json;charset=UTF-8", forHTTPHeaderField: "Content-Type")
        //
        request.timeoutInterval = 60.0
        //
        session.configuration.timeoutIntervalForRequest = 30.0
        // 构建请求任务
        let task = session.dataTask(with: request){ data, response, error in
            guard error == nil, let respData = data, let _:URLResponse = response else {
                print("请求出错")
                return
            }
            // data -> string
            let dataStr = String(data: respData, encoding: String.Encoding.utf8)!
            // data -> json
            let responseObject = strToObj(json: dataStr)
            print("GET 请求 的URL: \(getUrl)")
            print("GET 请求结果: \(dataStr)")
            print("GET 请求结果: \(responseObject)")
        }
        // 执行任务 发起请求
        task.resume()
    }
    
    /**
     * 进行 PSOT 请求
     */
    func doPost(){
        // 请求地址
        // let reqUrl = URL(string: "http://192.168.43.42:5000/user")!
        let reqUrl = URL(string: "http://192.168.137.1:5000/zip/packages")!
        // session 会话对象
        let session = URLSession.shared
        // 请求体
        var request = URLRequest(url: reqUrl)
        request.httpMethod = "POST"
        // 请求参数 body
        let paramJson: Dictionary<String,Any> = ["name":"lqk", "date":2023]
        let paramData = try! JSONSerialization.data(withJSONObject: paramJson, options: [])
        request.httpBody = paramData
        
        // 请求头
        request.addValue("application/json;charset=UTF-8", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json;charset=UTF-8", forHTTPHeaderField: "Accept")
        
        // 构建请求任务
        let task = session.dataTask(with: request) {data, response, error in
            guard error == nil, let respData = data, let _:URLResponse = response else {
                print("请求出错: \(error!.localizedDescription)")
                return
            }
            // POST请求内容
            print("POST 请求: URL= \(reqUrl) 参数: \(paramJson)")
            
            // data -> json 字符串
            let dataStr = String(data: respData, encoding: String.Encoding.utf8)!
            print("POST 请求结果: \(dataStr)")
            // string -> json 字典
            let responseObj = strToObj(json: dataStr)
            print("POST 请求结果: \(responseObj)")
            // 获取详细信息
            // let name = responseObj["name"].unsafelyUnwrapped
            // let age = responseObj["age"].unsafelyUnwrapped
            // print("POST 请求结果: \(name)")
            // print("POST 请求结果: \(age)")
        }
        // 执行任务 发起请求
        task.resume()
        
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
